<?php 
	$_SESSION['realpage'] = true;
	
	require_once "./class.Message.php";
 	require_once "./class.User.php";
 	require_once "./class.GeneralServices.php";
 	session_start();
 	//for debug
 	//$_SESSION['userObj']= GeneralServices::getService()->getUser(34);
 	
 	if(isset($_SESSION['userObj']))
 	{
 		if (!isset($_GET['friendId']) || !is_numeric($_GET['friendId']))
 		{
 			$_SESSION['error'] = 'can\'t get friend id';
 			require './error.php';
 			die(' ');
 		}
 		$friend = $_GET['friendId'];
 		$userObj = $_SESSION['userObj'];
 		$msgs = GeneralServices::getService()->getThread($userObj->uid,$friend,6,0);
 		//public function getThread($uid,$friend,$limit,$downpour)
 		
 		//get friend
 		$friendObj = GeneralServices::getService()->getUser($friend);
 		
		$numOfMsgs= count($msgs); 
 	}
 	else 
 	{
 		require './hack.php';
 	}
 	
 	?>
<!DOCTYPE HTML>
<html>
<head>
<?php require_once "./HtmlIncludes.php";?>
<title>Urban Dynamics</title>
</head>
<body>
<script>
//downpour for new msgs, in msgs it's uppour since it's by descending order
downpour = '<?php echo $msgs[0]->mid ; ?>' ;


function sendMsgToFriend()
{
	//do ajax
	if (window.XMLHttpRequest)
	  {// code for IE7+, Firefox, Chrome, Opera, Safari
	  xmlhttp=new XMLHttpRequest();
	  }
	else
	  {// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	  }
	xmlhttp.onreadystatechange=function()
	  {
	  if (xmlhttp.readyState==4 && xmlhttp.status==200)
	    {
		    if(xmlhttp.responseText == 'false')
		    {
		    	alert('error!');		    	
		    }
		    else
		    {
			   
        	    fname =  'to <?php echo $friendObj->FirstName; ?>';
        	    classname = 'PUserMessage';   

                jQuery(" <div />" )
	             .addClass( classname ) 
	             .html( "<div class=\"leftAlligned\">"
       	             + "<span class=\"leftAlligned\">"+fname+":</span> <br>"
       	             +"<div class=\"msgContent leftAlligned\">"+replaceBR($("#content").val())+"</div>"
       	             +" </div>"
						 +"<div class=\"msgDate rightAlligned\">a few seconds ago </div>"
       	             +"<br>"
   	         ).appendTo("#msgContainer");
      	       jQuery(" <br/>").appendTo("#msgContainer");
      	       
      	     $('#content').val(' ');
      	     window.scrollTo(0,$(window).scrollTop() + 2* $(window).height());
		    }
		}
	  };
	xmlhttp.open("GET","./ajax.php?method=sendMsg&friendid=<?php echo $friend; ?>&content="+replaceBR($('#content').val())+"&sid="+"<?php echo session_id(); ?>",true);
	xmlhttp.send();
	return false;
}

function refrsh()
{
	url = "./Thread.php?friendId=<?php echo $friend; ?>";						    	
	window.location.replace(url);
	return true;
}
function backtoInbox()
{
	url = "./Inbox.php";						    	
	window.location.replace(url);
	return true;
}

function getMoreMsgs(asd)
{
	if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
		    {
			    if(xmlhttp.responseText == '[]' || xmlhttp.responseText == '')
			    {
			    	$('#ThreadsMore').html('&nbsp;&nbsp;No previous messages found');			    
			   	}
			    else
			    {
			    	myuid = <?php echo $userObj->uid ;?>;
				    $tmp='';
				    objArr	 = jQuery.parseJSON(xmlhttp.responseText);
				    
				    for(i=objArr.length-1;i>=0;i--)
    			    {
				    	 $("#msgContainer").prepend("<br>");
        			    obj = objArr[i];
        			    fid = (myuid == obj.sender)? obj.receiver : obj.sender;
        			    fname =  (myuid == obj.sender)? 'to '+ obj.receiverName : 'from '+obj.senderName;
        			    classname = (myuid == obj.sender) ? 'PUserMessage' : 'FriendMessage';   
    					 	
        			    jQuery(" <div />" )
        	             .addClass( classname ) 
        	             .html( "<div class=\"leftAlligned\">"
                	             + "<span class=\"leftAlligned\">"+fname+":</span> <br>"
                	             +"<div class=\"msgContent leftAlligned\">"+shorten(obj.content)+"</div>"
                	             +" </div>"
								 +"<div class=\"msgDate rightAlligned\">"+obj.lostTime+" ago </div>"
                	             +"<br/>"
            	         ).prependTo("#msgContainer");
           	         
        			  
					  downpour = obj.mid; // set new downpour
    			    }
				}
			}
		};
		xmlhttp.open("GET","./ajax.php?method=getThread&friend=<?php echo $_GET['friendId'] ; ?>&sid=<?php echo session_id(); ?>&limit=5&downpour="+downpour,true);
		xmlhttp.send();
		return false;
}

function refreshMsgs()
{ 
	refrsh();
	return false;
}

</script>

    	<div class="PaneHeader">
    		<div class="leftAlligned">Thread with <?php echo $friendObj->FirstName; echo ' '.$friendObj->Surname; ?></div>
    		<div class="rightAlligned  buttons">
    			<div class="rightAlligned"  id='refreshBtn' > refresh </div>
    			&nbsp;
    			<div class="GetMoreMsgsButton rightAlligned"  id='gotoInbox' > inbox </div>
    			&nbsp;
    			<div class="GetMoreMsgsButton rightAlligned"  id='older' > get older.. </div>
    			
			</div>
     	</div>    	
     	<div id="ThreadsMore"></div>
    	<br>
				
		
		<div class = "msgCont" id="msgContainer" >
			<?php 
			foreach ($msgs as $msg)
			{
			?>
				<div class="<?php echo ($userObj->uid == $msg->sender)? 'PUserMessage' : 'FriendMessage'; ?>" >
					<div class="leftAlligned">
					 <span class="leftAlligned"> <?php 
					 if($userObj->uid == $msg->sender)
					 	echo 'to '.$msg->receiverName;
					 else  
					 	echo 'from '.$msg->senderName;
					 ?>:</span> <br>
					 <div class="msgContent leftAlligned"><?php echo $msg->content; ?></div>
					</div>
					<div class="msgDate rightAlligned"><?php echo $msg->timePassed().' ago'; ?></div>
				</div>
			<br>
			
			<?php } // end of loop
			?>			
		</div>
		
		<div class="InputsCont leftAlligned">
		<form action="function(){return false;}">
		<div class="msgContentToSend">
			<textarea style="background:#aed0ea;" cols="65" rows="5" name="content" id="content" class="innerCont leftAlligned  text ui-widget-content ui-corner-all innerCont"></textarea>
		</div>
		</form>
		<div class="rightAlligned" id="sendBtn">Send</div>
		</div>
	<script type="text/javascript">
	//scroll down
	window.scrollTo(0,$(window).scrollTop() + 2* $(window).height());

	$( "#refreshBtn" )
		.button()
		.click(function() {
			refreshMsgs();
		});
	$( "#gotoInbox" )
	.button()
	.click(function() {
		backtoInbox();
	});
	$( "#sendBtn" )
	.button()
	.click(function() {
		sendMsgToFriend();
	});
	$( "#older" )
	.button()
	.click(function() {
		getMoreMsgs();
	});
	</script>	
    </body>
</html>

<?php 
	$_SESSION['realpage'] = false;
?>